package com.zhy.changeskin.attr;


import com.zhy.changeskin.constant.SkinConfig;
import com.zhy.changeskin.utils.TextUtils;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import java.util.ArrayList;
import java.util.List;

public class SkinAttrSupport {

    private static SkinAttrType getSupportAttrType(String attrName) {
        for (SkinAttrType attrType : SkinAttrType.values()) {
           if (attrType.getAttrType().equals(attrName))
                return attrType;
        }
        return null;
    }

    /**
     * 传入abilityslice，找到content元素，递归遍历所有的子View，根据tag命名，记录需要换肤的View
     *
     * @param rootLayout    Root element of the Layout resource
     *
     * @return list of SkinView
     */
    public static List<SkinView> getSkinViews(ComponentContainer rootLayout) {
        List<SkinView> skinViews = new ArrayList<SkinView>();
        addSkinViews(rootLayout, skinViews);
        return skinViews;
    }

    public static void addSkinViews(Component component, List<SkinView> skinViews) {
        SkinView skinView = getSkinView(component);
        if (skinView != null) skinViews.add(skinView);

        if (component instanceof ComponentContainer) {
            ComponentContainer container = (ComponentContainer) component;

            for (int i = 0, n = container.getChildCount(); i < n; i++) {
                Component child = container.getComponentAt(i);
                addSkinViews(child, skinViews);
            }
        }
    }

    public static SkinView getSkinView(Component component) {
        if (component == null)
            return null;
        Object tag = component.getTag();
        if (tag == null) return null;
        if (!(tag instanceof String)) return null;
        String tagStr = (String) tag;

        List<SkinAttr> skinAttrs = parseTag(tagStr);
        if (!skinAttrs.isEmpty())
        {
            return new SkinView(component, skinAttrs);
        }
        return null;
    }

    //skin:left_menu_icon:src|skin:color_red:textColor
    private static List<SkinAttr> parseTag(String tagStr) {
        List<SkinAttr> skinAttrs = new ArrayList<SkinAttr>();
        if (TextUtils.isEmpty(tagStr)) return skinAttrs;

        String[] items = tagStr.split("[|]");
        for (String item : items) {
            if (!item.startsWith(SkinConfig.SKIN_PREFIX))
                continue;
            String[] resItems = item.split(":");
            if (resItems.length != 3)
                continue;

            String resName = resItems[1];
            String resType = resItems[2];

            SkinAttrType attrType = getSupportAttrType(resType);
            if (attrType == null) continue;
            SkinAttr attr = new SkinAttr(attrType, resName);
            skinAttrs.add(attr);
        }
        return skinAttrs;
    }
}
